<template>
	<custom-layout custom-class="custom-layout">
		<!-- 表单 -->
		<wd-form ref="formRef" :model="formData">
			<template v-for="(row,rowIndex) in formData.stageList" :key="row.id">
				<view class="cell-title">{{ row.stageName }}</view>
				<wd-cell-group border>
					 <wd-datetime-picker 
        			   v-model="formData.stageList[rowIndex].startTime"
						:prop="'stageList.' + rowIndex + '.startTime'"
        			    type="date" 
        			    :rules="getStartTimeRules(row,rowIndex)" 
        			    label="开工日期"
				
        			  />
					<wd-datetime-picker 
        			    v-model="formData.stageList[rowIndex].endTime"
						:prop="'stageList.' + rowIndex + '.endTime'"
        			    type="date" 
        			    :rules="getEndTimeRules(row, rowIndex)"
        			    label="完工日期" 
        			  />
					<wd-cell title="施工天数" required>
						<view class="content">{{ calculateDays(row.startTime, row.endTime) }} </view>
					</wd-cell>
				
		
			</wd-cell-group>
			</template>
		</wd-form>
		<!-- 提交 -->
		<wd-button block size="large" custom-class="submit-button" @click="handleSubmit">提交</wd-button>
		
	</custom-layout>
</template>

<script setup>
	import dayjs from 'dayjs';	
	import {
		reactive,
		ref
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		useDictionaryStore,
		useUserStore
	} from '@/store/index.js'
	import {
		engineeringStageExtensionApply,
	} from '@/api/engineering/detail.js'

	// 字典仓库
	const dictionaryStore = useDictionaryStore()
	// 用户仓库
	const userStore = useUserStore()
	
	// 表单ref
	const formRef = ref()
	// 表单数据
	const formData = ref({
		stageList: [],
		
	})
	const actualBeginTime = ref(null)
	const actualEndTime = ref(null)
	onLoad((option)=>{
		formData.value=JSON.parse(decodeURIComponent(option.row))
			
	})
	// 处理提交
	const handleSubmit = async () => {
		  console.log(formData.value,'formData.value');
		

		const validateResult = await formRef.value.validate()
		console.log('校验结果',validateResult);
		
		if (!validateResult.valid) return
		uni.showLoading({
			mask: true
		})
		const params = {
			contractId:formData.value.contractId,
			engineeringId:formData.value.engineeringId,
			orderId:formData.value.orderId,
			stageList:formData.value.stageList.map(node => ({
    		  id: node.id,
    		  stageName: node.stageName,
    		  endTime: node.endTime?dayjs(node.endTime).format('YYYY-MM-DD 23:59:59'):'',
    		  startTime: node.startTime?dayjs(node.startTime).format('YYYY-MM-DD 23:59:59'):''
    		}))
			

			
		}
		console.log(params,'params');
		
		engineeringStageExtensionApply(params).then(()=>{
			uni.navigateBack(); // 返回上一页
			uni.$emit('refresh-confirm-complete'); // 触发刷新线索列表
		}).catch((error) => {
			console.log(error);
			
			setTimeout(() => {
				uni.showToast({
					title: error,
					icon: 'none'
				})
			})
		}).finally(() => {
			uni.hideLoading()
			
		})
		
	}
	// 开工日期验证规则
  const getStartTimeRules = (row, rowIndex) => {
    return [
      { required: true, message: '请选择开工日期' },
      {
        validator: (value) => {
          if (!value || !row.endTime) return true;
          return dayjs(value).isBefore(dayjs(row.endTime));
        },
        message: '开工日期不能大于完工日期'
      },
      {
        validator: (value) => {
          if (!value || !formData.value.actualBeginTime) return true;
          return new Date(value).getTime() >= new Date(formData.value.actualBeginTime).getTime();
        },
        message: `开工日期不能早于${dayjs(formData.value.actualBeginTime).format('YYYY-MM-DD')}`
      }
    ];
  };

  // 完工日期验证规则
  const getEndTimeRules = (row, rowIndex) => {
    return [
      { required: true, message: '请选择完工日期' },
      {
        validator: (value) => {
          if (!value || !row.startTime) return true;
          return dayjs(value).isAfter(dayjs(row.startTime));
        },
        message: '完工日期不能小于开工日期'
      },
      {
        validator: (value) => {
          if (!value || !formData.value.actualEndTime) return true;
          return  new Date(value).getTime() < new Date(formData.value.actualEndTime).getTime();
        },
        message: `完工日期不能晚于${dayjs(formData.value.actualEndTime).format('YYYY-MM-DD')}`
      }
    ];
  };
	// 计算施工天数
const calculateDays = (startTime, endTime) => {
  if (!startTime || !endTime) return 0;

  const start = dayjs(startTime);
  const end = dayjs(endTime);

  if (start.isAfter(end)) {
    return 0; // 开工时间大于完工时间，返回0天
  }

  return end.diff(start, 'day') + 1; // 包含首尾两天
};
</script>

<style lang="scss" scoped>
	// 自定义布局
	:deep(.custom-layout) {
		background: #F8F8F8;
	}

	// 提交按钮
	:deep(.submit-button) {
		margin: 32rpx;
	}
	.cell-title {
		font-size: 30rpx;
		font-weight: bold;
		margin: 24rpx;
		padding-left: 10rpx;
		position: relative;
	}
	.cell-title:before {
		content: "";
		position: absolute;
		left: -2px;
		top: 15%;
		height: 70%;
		width: 6rpx;
		background-color: #6a9cff;
	}
</style>